<?php

declare(strict_types=1);

namespace app\admin;

use app\admin\middleware\Auth;
use think\facade\View;
use think\facade\Request;
use app\admin\middleware\Method;
use app\system\model\RoleMenu;
use app\admin\model\Message;

/**
 * 后台控制器基类
 * 需要登录的控制器请继承此控制器
 */
abstract class BaseAdminController extends BaseXpController
{

    /**
     * 是否来自iframe的请求
     * @var string
     */
    public $isFrame = '';

    /**
     * 初始化
     */
    public function initialize()
    {
        parent::initialize();
        // 中间件
        $this->middleware = [Auth::class, Method::class];
        // 登录信息
        $this->initUser();
        // 读取菜单
        $this->getMenu();
        // 判断是否来自iframe的请求
        $this->isIframe();
        // 读取我的消息
        $this->getMessage();
    }

    /**
     * 读取我的消息
     */
    protected function getMessage()
    {
        // 未读消息的数量
        $count = defined('UID') ? Message::where('admin_id', UID)->where('is_read', 0)->count() : 0;
        View::assign('top_message_count', $count);
        // 未读消息的列表(前10条)
        $list = defined('UID') ? Message::where('admin_id', UID)->where('is_read', 0)->limit(10)->order('id', 'desc')->column('title', 'id') : [];
        View::assign('top_message_list', $list);
    }

    /**
     * 判断是否来自iframe的请求
     */
    protected function isIframe()
    {
        $iframe = input('iframe', '');
        View::assign('iframe', $iframe);
        $this->isFrame = $iframe;
    }

    /**
     * 验证登录信息并获取登录账户信息
     */
    protected function initUser()
    {
        $auth = new Auth;
        $user = $auth->check();
        if ($user) {
            define('UID', $user->id);
            define('USERNAME', $user->nickname);
            define('USER', $user);
            View::assign('username', $user->nickname);
            $this->user = $user;
            // 读取数据权限
            $this->dataScope();
        }
    }

    /**
     * 根据角色获取出应用模块列表
     * @param array $arr 权限列表
     * @return array
     */
    private function getApps($arr)
    {
        $new = [];
        foreach ($arr as $value) {
            $ex = explode('/', $value);
            $new[] = $ex[0];
        }
        return array_unique($new);
    }

    /**
     * 读取菜单
     */
    protected function getMenu()
    {
        $role_id = defined('USER') ? USER->role_id : 0;
        $actions = RoleMenu::where('role_id', $role_id)->column('role_name');
        $apps = $this->getApps($actions);
        $menus = [];
        if ($this->menuFiles) {
            foreach ($this->menuFiles as $file) {
                $menu = require $file;
                $newMenu = $this->getPerms($menu, $actions, $apps);
                if ($newMenu) {
                    $menus[$menu['name']] = $newMenu;
                }
            }
        }
        // 排序
        usort($menus, function ($item1, $item2) {
            return $item1['priority'] <=> $item2['priority'];
        });
        $appName = app('http')->getName(); // 应用名称
        $baseUrl = Request::baseUrl();
        $splitUrl = explode('.html', $baseUrl);
        $routeUrl = $splitUrl[0]; // 当前路由
        View::assign('appName', $appName);
        View::assign('baseUrl', $routeUrl);
        View::assign('menus', $menus);
    }

    /**
     * 过滤菜单
     * @param array $menu 菜单
     * @param array $actions 权限列表
     * @param array $apps 应用模块列表
     * @return array
     */
    private function getPerms($menu, $actions, $apps)
    {
        $uid = defined('UID') ? UID : 0;
        if (!$this->shouldShowMenu($menu, $uid, $actions, $apps)) {
            return [];
        }
        $children = [];
        $subMenu = [];
        if (isset($menu['children']) && is_array($menu['children'])) {
            foreach ($menu['children'] as $child) {
                $filteredChild = $this->getPerms($child, $actions, $apps);
                if ($filteredChild) {
                    $children[] = $filteredChild;
                    $subMenu[] = '/' . $filteredChild['name'];
                }
            }
        }
        $menu['children'] = $children;
        $menu['subMenu'] = $subMenu;
        return $menu;
    }

    /**
     * 判断是否应该显示菜单
     * @param array $menu 菜单
     * @param int $uid 用户ID
     * @param array $actions 权限列表
     * @param array $apps 应用模块列表
     * @return bool
     */
    private function shouldShowMenu($menu, $uid, $actions, $apps)
    {
        return $menu['show'] && (
            $uid == 1 || (
                $actions &&
                $apps &&
                (in_array($menu['name'], $apps) || in_array($menu['name'], $actions))
            )
        );
    }

    /**
     * 404 页面 - 未找到页面
     */
    public function E404()
    {
        if (Request::isAjax()) {
            return json(['msg' => '抱歉，未找此页面！']);
        }
        $ext = $this->isFrame ? '?iframe=1' : '';
        return redirect('/admin/dashboard/message404' . $ext);
    }

    /**
     *  403 页面 - 无权限访问
     */
    public function E403()
    {
        if (Request::isAjax()) {
            return json(['msg' => '抱歉，您无权访问此页面！']);
        }
        $ext = $this->isFrame ? '?iframe=1' : '';
        return redirect('/admin/dashboard/message' . $ext);
    }

    /**
     * 演示数据无法操作
     */
    public function isDemo()
    {
        if (Request::isAjax()) {
            return json(['msg' => '演示数据无法操作']);
        }
        $ext = $this->isFrame ? '?iframe=1' : '';
        return redirect('/admin/dashboard/message' . $ext);
    }
}
